<template>
  <canvas ref="canvas"></canvas>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, watch } from "vue";
import {
  Chart,
  ArcElement,
  Tooltip,
  Legend,
  Title,
  DoughnutController, // 保持引用
} from "chart.js";
import { useI18n } from "vue-i18n"; // 引入 useI18n

// 注册所需的图表类型和组件
Chart.register(ArcElement, Tooltip, Legend, Title, DoughnutController);

interface ChartDataItem {
  name: string;
  value: number;
}

export default defineComponent({
  props: {
    data: {
      type: Array as () => ChartDataItem[],
      required: true,
    },
  },
  setup(props) {
    const { t, locale } = useI18n(); // 使用 useI18n 获取 t 方法和 locale
    const canvas = ref<HTMLCanvasElement | null>(null);
    let chart: Chart | null = null; // 用于存储图表实例

    const drawChart = () => {
      if (chart) {
        chart.destroy(); // 如果图表实例已存在，先销毁它
      }
      if (canvas.value) {
        const ctx = canvas.value.getContext("2d");
        if (ctx) {
          chart = new Chart(ctx, {
            type: "doughnut", // 将类型改为 doughnut
            data: {
              labels: props.data.map((item) => item.name),
              datasets: [
                {
                  data: props.data.map((item) => item.value),
                  backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56",
                    "#4BC0C0",
                    "#9966FF",
                  ],
                },
              ],
            },
            options: {
              responsive: true,
              plugins: {
                legend: {
                  position: "bottom",
                },
                title: {
                  display: true,
                  text: t("ui.pieChart.title"),
                },
              },
            },
          });
        }
      }
    };

    onMounted(() => {
      drawChart();
    });
    // 监视 data 属性的变化
    watch(() => props.data, drawChart);

    // 监视 locale 的变化，重新绘制图表
    watch(locale, () => {
      drawChart(); // 切换语言时重新绘制图表
    });

    return { canvas };
  },
});
</script>

<style scoped>
canvas {
  max-width: 100%;
}
</style>
